// 目标预算（集团下发）
<template>
    <div class="e-form">
        <div class="tabs warningTabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag">
                </el-tab-pane>
                <el-tab-pane label="预算清单" name="budgetList" :disabled="clickTabFlag">
                </el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag">
                </el-tab-pane>
                <el-tab-pane label="审核历史" name="auditHistory" :disabled="clickTabFlag">
                </el-tab-pane>
                <el-tab-pane label="变更历史" name="changeHistory" :disabled="clickTabFlag">
                </el-tab-pane>
                <div>
                    <!-- 基本信息 -->
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form :model="formData" label-width="200px">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="项目名称：">
                                            <span>{{formData.projectName}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="项目编号：">
                                            <span>{{formData.projectNo}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="不含税预算金额（万元）：">
                                            <span>{{convertToWanYuang(formData.taxExcludedBudgetAmount)}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="税率（%）：">
                                            <span>{{formData.taxRate}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="税额：">
                                            <span>{{formData.taxAmount}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="集团下发预算金额（万元）">
                                            <span>{{convertToWanYuang(formData.budgetIssuedAmount)}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="币种：">
                                            <span>{{formData.currency}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="承建机构：">
                                            <span>{{formData.constructionOrgName}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="编制机构：">
                                            <span>{{formData.orgName}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="状态：">
                                            <span>{{statusLable(formData.state)}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="备注：">
                                            <span>{{formData.remarks}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="人民币汇率：">
                                            <span>{{formData.rmbRate}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row v-if="state === 5">
                                    <el-col :span="12">
                                        <el-form-item label="作废人：">
                                            <span>{{ formData.nullifyCreator }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="作废原因：">
                                            <span>{{formData.nullifyReason }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row v-if="state === 5">
                                    <el-col :span="12">
                                        <el-form-item label="作废说明：">
                                            <span>{{
                                                formData.nullifyDescription
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                        <el-col :span="12">
                                        <el-form-item label="作废时间：">
                                            <span>{{
                                                formData.nullifyCreated
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <!-- 预算清单  -->
                    <div id="budgetListCon" class="con">
                        <div class="tabs-title" id="budgetList">预算清单</div>
                        <div class="e-tree-table" >
                            <div class="top">
                                <div class="left">
                                    <div>
                                        <span>结构细目维度:</span>
                                        <el-radio-group v-model="veidoo" @change="toggleDetail">
                                            <el-radio :label="true">结构名称-->细目</el-radio>
                                            <el-radio :label="false">细目-->结构名称</el-radio>
                                        </el-radio-group>
                                    </div>
                                    <!-- <div class="box" @click="toggleDetail">
                                        <img class="icon" src="@/assets/switch.png" title="结构细目维度">
                                        <div class="iconFont">结构细目维度</div>
                                    </div> -->
                                </div>
                            </div>
                            <!-- 细目-结构 -->
                            <el-table key="a" v-if="!veidoo"
                                class="table"
                                :data="budgetListTable"
                                border
                                style="width: 100%"
                                row-key="billId"
                                lazy
                                :load="onload"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                            >
                                <el-table-column label="操作" width="100" align='left'>
                                </el-table-column>
                                <el-table-column prop="itemNo" label="细目编号" min-width="150" show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column prop="identification" label="标识" min-width="100" show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column prop="itemName" label="细目名称" min-width="200" show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column prop="structureName" label="结构名称" min-width="200" show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column prop="unit" label="单位" width="120">
                                </el-table-column>
                                <el-table-column prop="quantity" label="数量" width="150">
                                </el-table-column>
                                <el-table-column prop="budgetPrice" label="预算单价" width="130">
                                </el-table-column>
                                <el-table-column prop="budgetAmount" label="预算金额" width="130">
                                </el-table-column>
                            </el-table>
                            <!-- 结构-细目 -->
                            <el-table key="b" v-else
                                class="table"
                                :data="budgetListTable1"
                                border
                                style="width: 100%"
                                row-key="billId"
                                lazy
                                :load="onload"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                            >
                                <el-table-column label="操作" width="100" align='left'>
                                </el-table-column>
                                <el-table-column prop="structureName" label="结构名称" min-width="200" show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column prop="identification" label="标识" min-width="100" show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column prop="itemNo" label="细目编号" min-width="150" show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column prop="itemName" label="细目名称" min-width="200" show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column prop="unit" label="单位" width="120">
                                </el-table-column>
                                <el-table-column prop="quantity" label="数量" width="150">
                                </el-table-column>
                                <el-table-column prop="budgetPrice" label="预算单价" width="130">
                                </el-table-column>
                                <el-table-column prop="budgetAmount" label="预算金额" width="130">
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <!-- 附件信息 -->
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp :relationId="attachId" isView bucketName="project" />
                    </div>

                    <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                billType="6061"
                                :tableData.sync="auditHistoryTable"
                                @getAuditHistory="getAuditHistory"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>

                    <!-- 变更历史 -->
                    <div id="changeHistoryCon" class="con">
                        <div class="tabs-title" id="changeHistory">变更历史</div>
                        <div class="e-table">
                            <el-table
                                class="table"
                                :data="changeHistoryTable"
                                border
                                ref="changeHistorySelect"
                            >
                                <el-table-column prop="changeBillNo"  align="center" label="项目编号" min-width="200" show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column
                                    prop="billDate"
                                    label="项目名称"
                                    width="150"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="orgName"
                                    label="承建单位"
                                    show-overflow-tooltip min-width="200"
                                    align="left"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="number"
                                    label="期数"
                                    width="80"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="orgName"
                                    label="截止上期末含税预算金额"
                                    show-overflow-tooltip width="180"
                                    align="left"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="orgName"
                                    label="本次变更金额"
                                    show-overflow-tooltip width="150"
                                    align="left"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="orgName"
                                    label="截止本期末含税预算金额"
                                    show-overflow-tooltip width="180"
                                    align="left"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="orgName"
                                    label="预算编制机构"
                                    show-overflow-tooltip width="180"
                                    align="left"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="state"
                                    label="状态"
                                    width="100"
                                    align="center"
                                >
                                    <template slot-scope="{row}">
                                        <span>{{statusLable(row.state)}}</span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                </div>
            </el-tabs>
        </div>
        <div class="buttons">
            <el-button
                type="primary"
                class="btn-blue"
                v-if="statusLable(state) !== '草稿'"
                size="small"
                v-debounce
                >打印</el-button
            >
            <ComExaButtons :auditState="auditState" @exas="exas" v-if="statusLable(state) !== '已作废'"/>
            <el-button size="small" @click="handleClose" v-debounce>取消</el-button>
        </div>
        <div id="seat" :style="{height: seatHeight + 'px'}"></div>
    </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import $ from 'jquery'
import '@/utils/jquery.scrollTo.min'
import request from '@/api/projectManagement/targetBudget.js'
import ComAuditHistoryIndex from '@/pages/equipment/components/auditHistory/auditHistoryIndex'
import { getCurrentUnitInfo, audit, nullify, undoworkt, history } from '@/api/projectManagement/audit.js'
import { openAppClient, hideLoading, showLoading } from '@/utils/common'
import ComExaButtons from '@/pages/equipment/components/auditHistory/exaButtons'
import AttachComp from '@/components/common/attachIndex'
export default {
    data () {
        return {
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            formData: {
               	'billId': '',
                'budgetIssuedAmount': 0,
                'changeButtonState': true,
                'constructionOrgId': '',
                'constructionOrgName': '',
                'currency': '',
                'currencyId': '',
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'orgId': '',
                'orgName': '',
                'projectId': '',
                'projectName': '',
                'projectNo': '',
                'remarks': '',
                'rmbRate': 0,
                'state': 0,
                'taxAmount': 0,
                'taxExcludedBudgetAmount': 0,
                'taxRate': 0,
                'workId': ''
            },
            // this.$route.query.billid
            billid: this.$route.query.billid, //测试暂时写死
            budgetListTable: [], //细目-结构清单信息表格
            budgetListTable1: [], //机构-细目清单信息表格
            auditHistoryTable: [], //审核历史
            attachTableData: [], //附件信息表格
            changeHistoryTable: [], //变更历史
            auditState: {}, //流程按钮显示状态
            isSearch: false, //是否是搜索
            veidoo: true, //默认为 结构-细目
            auditParams: {
                'isPass': true,
                'opinion': '',
                'isShareInAudit': true,
                'freeNextUser': '',
                'freeNextUnitIndex': 0,
                'billId': '',
                'billType': 6061
            },
            nullifyParams: { //作废
                'billId': '',
                'billType': 6061,
                'nullifyReason': '',
                'nullifyDescription': ''
            },
            auditHistoryParams: {
                'billId': '',
                'billType': 6061
            },
            isToggle: false, //是否切换结构细目维度 默认是细目->结构
            distributionToList: { //细目->结构
                'billId': '',
                'parentId': '0' //首级默认为0,下级传本级id
            },
            listToDistribution: { //结构->细目
                'billId': '',
                'parentId': '0'
            },
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
        }),
        statusLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.state
                const obj = state.find(x=>x.value === param)
                return obj ? obj.label : ''
            }
        },
        //元转换为万元
        convertToWanYuang () {
            return val =>{
                let num = Number(val)
                if (num == 0) {
                    return num
                } else
                if (num > 1 && num < 10000) {
                    return num
                } else {
                    return (num  / 10000).toFixed(5)
                }
            }
        },
        //当前单据状态
        state () {
            return this.formData.state
        },
        attachId () {
            return this.$route.query.billid
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        showAddress () {
            return value=>{
                if(!value) return ''
                const obj = JSON.parse(value)
                const address = obj.address ? obj.address.join('-') : ''
                const detail = obj.detail
                let str = ''
                if(address && detail) {
                    str = address + '-' + detail
                }else if(!address  && detail) {
                    str = detail
                }else if(address  && !detail) {
                    str = address
                }
                return str
            }
        }
    },
    components: {
        ComAuditHistoryIndex,
        ComExaButtons,
        AttachComp
    },
    created () {
        this.auditParams.billId = this.billid
        this.nullifyParams.billId = this.billid
        this.auditHistoryParams.billId = this.billid
        this.distributionToList.billId = this.billid
        this.listToDistribution.billId = this.billid
    },
    mounted () {
        this.init()
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'budgetList', 'attach', 'auditHistory', 'changeHistory']
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    console.log('item', item)
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if ((scrollTop + 1) >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth
        this.screenHeight = document.documentElement.clientHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth
            this.screenHeight = document.documentElement.clientHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
    },
    methods: {
        ...mapMutations(['setAuditParams']),
        //初始化数据
        init () {
            showLoading()
            Promise.all([
                this.getBaseInfo(),
                this.getChangeHistory(),
                this.getStructureToListInfo(),
                this.getAuditHistory(),
                this.getCurrentUnitInfo(),
            ]).finally(() => {
                hideLoading()
            })
        },
        //获取基本信息
        getBaseInfo () {
            request.getGroupTargetById(this.billid).then(res=>{
                this.formData = res
            })
        },
        //获取变更历史
        getChangeHistory () {
            request.getChangeHistory(this.billid).then(res=>{
                this.changeHistoryTable = res
            })
        },
        //获取清单信息 细目->结构
        getListInfo () {
            request.getListToStructure(this.distributionToList).then(res=>{
                res.forEach(item=>{
                    item.hasChildren = item.isDetailed ? false : true  //是否子级  0不是 1是
                    item.children = []
                })
                this.budgetListTable = res
            })
        },
        //获取清单信息 默认 结构->细目
        getStructureToListInfo () {
            request.getStructureToList(this.listToDistribution).then(res=>{
                res.forEach(item=>{
                    item.hasChildren = item.isDetailed ? false : true  //是否子级  0不是 1是
                    item.children = []
                })
                this.budgetListTable1 = res
            })
        },
        //获取子级的数据
        async getChildrenInfo (thisLevelId) {
            //if是true 结构->细目 false 细目->结构
            if(this.veidoo) {
                this.listToDistribution.parentId = thisLevelId
                let result = await request.getStructureToList(this.listToDistribution) //结构->细目
                result.forEach(item=>{
                    item.hasChildren = item.isDetailed ? false : true  //是否子级 0不是 1 是
                    item.children = []
                })
                return result
            }else{
                this.distributionToList.parentId = thisLevelId
                let result = await request.getListToStructure(this.distributionToList) //细目->结构
                result.forEach(item=>{
                    item.hasChildren = item.isDetailed ? false : true  //是否子级 0不是 1 是
                    item.children = []
                })
                return result
            }
        },
        //懒加载数据
        async onload (row, treeNode, resolve) {
            let result
            if(row.children.length > 0) {
                result = row.children
            }else{
                //如果不是子级，就从接口取
                if (!row.isDetailed) {
                    result = await this.getChildrenInfo(row.thisLevelId) //本级id
                }else {
                    //是最子级，则初始为空，合并新增数据，并设为非最子级
                    result = []
                    row.isDetailed = false
                }
            }
            resolve(result)

        },
        //切换结构细目维度
        toggleDetail () {
            //if是true 结构->细目 false 细目->结构
            this.veidoo ? this.getStructureToListInfo() : this.getListInfo()
        },
        //刷新历史审核列表
        getAuditHistory () {
            history(this.auditHistoryParams).then(res=>{
                this.auditHistoryTable = res
            })
        },
        //获取状态按钮
        getCurrentUnitInfo () {
            getCurrentUnitInfo(this.auditHistoryParams).then(res => {
                this.auditState = res
            })
        },
        //取消
        handleClose () {
            //this.$router.replace('/leaseAcceptanceList')
        },
        //===============审核=================
        async exas (arg) {
            if (arg === 'audit') {
                this.setAuditParams(this.auditParams)
                // 客户端弹窗弹出本地页面
                openAppClient('/exaDialog', '填写审核意见', () => {
                    const auditParams = JSON.parse(localStorage.vuex).auditParams
                    audit(auditParams).then(() => {
                        this.clientPop('suc', '审核成功', this.handleClose)
                        // this.init()
                    })
                })
            } else if (arg === 'undoAudit') {
                this.clientPop('info', this.undoAudit, ()=>{
                    undoworkt(this.auditHistoryParams).then(() => {
                        this.clientPop('suc', '撤回成功', this.handleClose)
                    })
                })
            }else if (arg === 'nullify') {
                this.setAuditParams(this.nullifyParams)
                // 客户端弹窗弹出本地页面
                openAppClient('/nullifyDialog', '单据作废原因', () => {
                    const auditParams = JSON.parse(localStorage.vuex).auditParams
                    nullify(auditParams).then(() => {
                        this.clientPop('suc', '作废成功', this.handleClose)
                    })
                })
            }
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            console.log('clickTabFlag: ', this.clickTabFlag)
            $.scrollTo(`#${e.name}`, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}
.e-table {
    background: #fff;
}
.e-tree-table{
    background: #fff;
 }
.mainTitle{
    box-sizing: border-box;
    width:100%;
    height: 40px;
    line-height: 40px;
    background: rgb(246,246,246);
    border: 1px solid rgb(236, 236, 236);
    margin: auto;
    margin-bottom: 15px;
    padding-left: 10px;
}
.box{
    width: 90px;
    height: 55px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}
.box:hover{
    background: rgb(205,205,205);
    border-radius: 8px;
}
.icon{
    width: 30px;
    height: 30px;
}
.iconFont{
    font-size: 14px;
}
</style>
